<template>
  <div class="app-container">
    <el-row type="flex" align="middle">
      <el-col>
        <div style="display: flex; align-items: center;" class="dropdown">
          <span class="frequency">刷新频率:</span>
          <el-dropdown size="small" split-button type="primary" class="dropdown" @command="handleCommand">
            {{ selectedTime }}
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="time in timeOptions" :key="time" :command="time">{{ time }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-col>
    </el-row>
    <!--    生产任务数据-->
    <el-row :gutter="20" style="margin-top: 10px;" class="top-box">
      <el-col :span="15" :xs="24" style="max-height: 250px; overflow-y: auto;">
          <el-table
            :data="taskListWithEmptyRows"
            border
            height="100%"
            style="width: 100%">
            <el-table-column
              prop="name"
              label="生产任务"
              header-align="center"
              align="center" width="180px">
            </el-table-column>
            <el-table-column
              prop="totalCar"
              label="总任务车辆"
              header-align="center"
              align="center" min-width="90px">
            </el-table-column>
            <el-table-column
              prop="completedCar"
              label="已完成车辆"
              header-align="center"
              align="center" min-width="90px">
            </el-table-column>
            <el-table-column
              prop="incompleteCar"
              label="未完成车辆"
              header-align="center"
              align="center" min-width="90px">
            </el-table-column>
            <el-table-column
              prop="startTime"
              label="开始时间"
              header-align="center"  width="170px"
              align="center">
            </el-table-column>
            <el-table-column
              prop="endTime"
              label="结束时间"
              header-align="center" width="170px"
              align="center">
            </el-table-column>

            <el-table-column
              prop="practicalStartTime"
              label="实际开始时间"
              header-align="center"  width="170px"
              align="center">
            </el-table-column>
            <el-table-column
              prop="practicalEndTime"
              label="实际结束时间"
              header-align="center" width="170px"
              align="center">
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-flag"
                  @click="openKai(scope.row)"
                >开工</el-button>
              </template>
            </el-table-column>

          </el-table>
      </el-col>
      <el-col :span="9" :xs="24" style="max-height: 250px; overflow-y: auto;">
        <el-table
          ref="myTable"
          :data="solutionListWithEmptyRows"
          border
          height="100%"
          style="width: 100%"
          @cell-mouse-enter="stopScrollFn"
          @cell-mouse-leave="autoScrollFn">
          <el-table-column
            prop="taskName"
            label="生产任务"
            width="180px"
            header-align="center"
            align="center">
          </el-table-column>
          <el-table-column
            prop="carOrder"
            label="车序"
            width="100px"
            header-align="center"
            align="center">
          </el-table-column>
          <el-table-column
            prop="solutionDescribe"
            label="实时调度建议"
            header-align="center" show-overflow-tooltip min-width="130px">
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-divider class="el-divider1"></el-divider>
    <!--    <el-row :gutter="20">
          <el-col :span="4" v-for="(device, deviceIndex) in processes" :key="deviceIndex">
            <el-card :class="{'blue-background': isBlue(device)}">
              <div style="padding: 0px;" class="cardInfo" align="center">
                <span>{{device}}</span><br>
                <img src='../images/jiantou.jpg' class="image">
              </div>
            </el-card>
              <img :src="getImageSrc(device)" v-if="getImageSrc(device)" class="image" alt="" :hidden="getImageSrc(device)">
          </el-col>
        </el-row>-->
    <!-- 工序流程部分-->
    <el-row :gutter="20">
      <el-col :span="3" :xs="24">
        <div style="margin-left: 30px">
          <div style="display: flex; align-items: center;">
            <span style="font-size: 18px;font-weight: bold">启动：</span>
            <div style="margin-left: 15px"><img src='@/images/deng1.png' class="image" alt=""></div>
          </div>
          <div style="display: flex; align-items: center; margin-top: 8px">
            <span style="font-size: 18px;font-weight: bold">停止：</span>
            <div style="margin-left: 15px"><img src='@/images/deng3.png' class="image" alt=""></div>
          </div>
          <div style="display: flex; align-items: center; margin-top: 8px">
            <span style="font-size: 18px;font-weight: bold">异常：</span>
            <div style="margin-left: 15px"><img src='@/images/deng2.png' class="image" alt=""></div>
          </div>
        </div>
      </el-col>

      <el-col :span="21" :xs="24">
        <!--第一部分 -->
        <el-row v-for="(line, lineIndex) in lineList" :key="lineIndex">
          <div class="box" style="display: flex">
            <div class="box1 children1">
              {{line.twoLineName}}-{{line.threeLineName}}
            </div>
            <div class="box1 children2">
              <el-col :span="4" v-for="(device, deviceIndex) in processes" :key="deviceIndex" :xs="24" class="middle">
                <div style="height: 50px" class="card">
                  <div style="padding: 0px;" class="cardInfo1" align="center" :class="{'blue-background': isBlue(device)}">
                    <span>{{device}}</span><br>
                  </div>
                  <div class="cardInfo2"  v-if="deviceIndex !== processes.length - 1">
                    <img src='@/images/jiantou.jpg' class="image1">
                  </div>
                  <div v-if="device.includes('一焊')">
                    <div v-for="(processItem, lineItemIndex) in line.processList" :key="lineItemIndex">
                      <div v-if="processItem.processName.includes('一焊')">
                        <div v-for="(deviceItem, deviceItemIndex) in processItem.znddDevices" :key="deviceItemIndex">
                          <div :class="getIndexClass(lineIndex,deviceItemIndex)">
                            <el-tooltip class="item" effect="dark" :content="deviceItem.deviceName" :placement="getPlacementImg(lineIndex)">
                              <img :src="getImageSrc(deviceItem.deviceStatus)" class="image" alt="">
                            </el-tooltip>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else-if="device.includes('二焊')">
                    <div v-for="(processItem, lineItemIndex) in line.processList" :key="lineItemIndex">
                      <div v-if="processItem.processName.includes('二焊')">
                        <div v-for="(deviceItem, deviceItemIndex) in processItem.znddDevices" :key="deviceItemIndex">
                          <div :class="getIndexClass(lineIndex,deviceItemIndex)">
                            <el-tooltip class="item" effect="dark" :content="deviceItem.deviceName" :placement="getPlacementImg(lineIndex)">
                              <img :src="getImageSrc(deviceItem.deviceStatus)" class="image" alt="">
                            </el-tooltip>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else-if="device.includes('三焊')">
                    <div v-for="(processItem, lineItemIndex) in line.processList" :key="lineItemIndex">
                      <div v-if="processItem.processName.includes('三焊')">
                        <div v-for="(deviceItem, deviceItemIndex) in processItem.znddDevices" :key="deviceItemIndex">
                          <div :class="getLamdClass(lineIndex)">
                            <el-tooltip class="item" effect="dark" :content="deviceItem.deviceName" :placement="getPlacementImg(lineIndex)">
                              <img :src="getImageSrc(deviceItem.deviceStatus)" v-if="getImageSrc(deviceItem.deviceStatus)" class="image" alt="">
                            </el-tooltip>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </div>
          </div>
        </el-row>
      </el-col>

    </el-row>
    <el-divider class="el-divider2"></el-divider>
    <div class="m50">
      <!-- 下方表格 -->
      <el-table border style="margin-top: 20px;" :data="transData" :span-method="objectSpanMethod" :cell-style="customCellStyle"
                :header-cell-style="handerMethod" :row-class-name="tableRowClassName">
        <el-table-column v-for="(item, index) in transTitle" :label="item" span="2" :key="index"  align="center">
          <template slot-scope="scope">
            {{scope.row[index]}}
          </template>
        </el-table-column>
      </el-table>
    </div>


    <el-dialog title="人员分配" :visible.sync="dialogFormVisible" width="500px" append-to-body>
      <el-form :model="formPeople" label-width="80px">

        <el-form-item label="当前任务" >
          <el-input v-model="formPeople.name" disabled autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="人员">
          <el-checkbox-group v-model="formPeople.peopleIds">
            <el-checkbox label="人员 A" ></el-checkbox>
            <el-checkbox label="人员 B" ></el-checkbox>
            <el-checkbox label="人员 C" ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="kaiGong()">确 定</el-button>
      </div>
    </el-dialog>


  </div>


</template>

<script>
import { selectTaskList ,selectSolutionList,getLineData,getWorkOrderData} from "@/api/zndd/intelligence/pageHome";
import {  kaiGong111 } from '@/api/zndd/work/workorder'

export default {
  name: 'pageHome',
  data() {
    return {
      formPeople:{name:null,peopleIds:[]},
      dialogFormVisible:false,
      // originData 为后端原始正常的数据, 此数据按正常表格展示 一行一行的数据
      // 保证数组里每一个对象中的字段顺序, 从上到下 一次对应显示表格中的从左到右
      originTitle: ['工单编号','任务开始时间', '已进行时间', '任务剩余时间','当前任务状态','工序剩余任务'], // originTitle 该标题为 正常显示的标题, 数组中的顺序就是上面数据源对象中的字段标题对应的顺序
      transTitle: ['', '一拼','一焊', '二拼', '二焊','三焊','补焊', '','', '','','',''], // transTitle 该标题为转化后的标题, 注意多一列,  因为原来的标题变成了竖着显示了, 所以多一列标题, 第一个为空即可
      transData: [],
      taskList: [],
      solutionList: [],
      lineList: [],
      workOrderList: [],
      znddWorkOrderStatusS: [],
      selectedTime: '5秒钟',
      allTimes: ['5秒钟', '10秒钟', '20秒钟', '30秒钟', '40秒钟', '50秒钟'],
      processes: ['一拼', '一焊', '二拼', '二焊', '三焊', '补焊'],
      imageTemp:'',
      placementImg : '',
    };
  },
  methods: {
    kaiGong(){
      kaiGong111(this.formPeople.name).then(response => {
        console.log(response);
        console.log(this.formPeople);
        this.$modal.msgSuccess("该任务已开工");
        this.dialogFormVisible=false;
      })
    },
    openKai(row){
      this.formPeople.name=row.name;
      this.dialogFormVisible=true;
    },
    // 表格自动滚动
    autoScrollFn() {
      clearInterval(this.scrollTimer);
      this.$nextTick(() => {
        const tBody = this.$refs.myTable.bodyWrapper;
        // 当可视窗口高度大于表格高度时，不滚动
        if (tBody.clientHeight > tBody.scrollHeight) {
          console.log(tBody.clientHeight);
          console.log(tBody.scrollHeight)
          return;
        }
        this.scrollTimer = setInterval(() => {
          tBody.scrollTop += 1; // 每次上滑一个像素
          // 当滚动到最底部(可视高度+距离顶部=整个高度)时，从头开始滚
          if (tBody.clientHeight + Math.round(tBody.scrollTop) === tBody.scrollHeight) {
            tBody.scrollTop = 0;
          }
        }, (1000 / 60) * 3); // 1000 / 60
      });
    },


    stopScrollFn() {
      clearInterval(this.scrollTimer);
      this.scrollTimer = null;
    },

    customCellStyle({ row, column, rowIndex, columnIndex }) {
      // 判断是否是最后一行
      if (rowIndex === this.transData.length - 1) {
        return { borderTop: '2px solid'};
      }
      return {};
    },
    // 下方表格的样式
    tableRowClassName({ rowIndex }) {
      if (rowIndex === this.transData.length - 1) {
        return 'last-row';
      }
      return '';
    },
    //灯泡提示
    getPlacementImg(index){
      if (index ===0){
        return this.placementImg = 'top';
      } else if (index ===1){
        return this.placementImg = 'bottom';
      }
    },
    getIndexClass(index1, index2) {
      // 根据下标的奇偶性返回对应的类名
      if (index1 % 2 === 0) {
        if (index2 % 2 === 0){
          return 'even-index1';
        } else {
          return 'odd-index1';
        }

      } else {
        if (index2 % 2 === 0){
          return 'even-index2';
        }else {
          return 'odd-index2';
        }
      }
    },
    getLamdClass(index) {
      // 根据下标的奇偶性返回对应的类名
      if (index % 2 === 0) {
        return 'lamp2';
      } else {
        return 'lamp1';
      }
    },
    //隐藏表头
    handerMethod({ row, column, rowIndex, columnIndex }) {
      if (row[0].level == 1) {
        //这里有个非常坑的bug 必须是row[0]=0 row[1]=2才会生效
        row[1].colSpan = 2
        row[2].colSpan = 2
        row[3].colSpan = 2
        row[4].colSpan = 2
        row[5].colSpan = 2
        row[6].colSpan = 2
        if (columnIndex === 0) {
          return { display: '' }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    },
    isBlue(device) {
      return ['一焊', '二焊', '三焊'].includes(device);
    },
    getImageSrc(device) {
      switch (device) {
        case '1':
          return require("@/images/deng1.png");
        case '2':
          return require("@/images/deng3.png");
        case '3':
          return require("@/images/deng2.png");
        default:
          return '';
      }
    },
    //定时器相关
    startTimer() {
      this.timer = setInterval(() => {
        // 在这里添加你需要定时执行的逻辑
        this.getTaskList();
        this.getSolutionList();
        this.getLineData();
        this.getWorkOrderData();
        // console.log('定时器触发');
      }, this.timeInMilliseconds);
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    resetTimer() {
      this.clearTimer();
      this.startTimer();
    },
    handleCommand(command) {
      this.selectedTime = command;
    },
    //查询任务信息列表
    getTaskList(){
      selectTaskList().then(response => {
          this.taskList = response;
        }
      );
    },
    //查询任务调度数据
    getSolutionList() {
      selectSolutionList().then(response => {
          this.solutionList = response;
        }
      );
    },
    //查询产线数据
    getLineData() {
      getLineData().then(response => {
          this.lineList = response;
        }
      );
    },
    //查询工单数据
    getWorkOrderData() {
      getWorkOrderData().then(response => {
          this.workOrderList = response;
          // 对每个工单数据进行格式化
          this.workOrderList.forEach(item => {
            item.workOrderStauts = this.znddWorkOrderFormatter(item.workOrderStauts);
          });
        }
      );
    },
    //格式化工单类型类型
    znddWorkOrderFormatter(info){
      const znddWorkOrder = this.znddWorkOrderStatusS.find(znddWorkOrder => znddWorkOrder.dictValue === info);
      return znddWorkOrder ? znddWorkOrder.dictLabel : '';
    },
  },
  computed: {
    //空白列计算
    taskListWithEmptyRows() {
      const emptyRowsNeeded = 3 - this.taskList.length;
      return this.taskList.concat(Array(Math.max(emptyRowsNeeded, 0)).fill({}));
    },
    solutionListWithEmptyRows() {
      const emptyRowsNeeded = 3 - this.solutionList.length;
      return this.solutionList.concat(Array(Math.max(emptyRowsNeeded, 0)).fill({}));
    },
    timeOptions() {
      return this.allTimes.filter(time => time !== this.selectedTime);
    },
    timeInMilliseconds() {
      const seconds = parseInt(this.selectedTime.replace('秒钟', ''), 10);
      return seconds * 1000;
    }
  },
  created() {
    this.autoScrollFn();
    this.stopScrollFn();
    this.getDicts("zndd_worker_order_status").then(response => {
      this.znddWorkOrderStatusS = response.data;
    });
    // 获取任务信息列表
    this.getTaskList();
    // 获取解决方案列表
    this.getSolutionList();
    // 获取产线数据
    this.getLineData();
    // 获取工单数据
    this.getWorkOrderData();
    // 数组按矩阵思路, 变成转置矩阵

    // 初始化定时器
    this.startTimer();
  },
  beforeDestroy() {
    // 清除定时器
    this.clearTimer();
  },
  watch: {
    selectedTime() {
      // 当 selectedTime 改变时，重新设置定时器
      this.resetTimer();
    },
  },
  beforeUpdate() {
    let matrixData = this.workOrderList.map((row) => {
      let arr = []
      for (let key in row) {
        // 判空处理
        arr.push(row[key] !== undefined && row[key] !== null ? row[key] : '')
      }
      return arr
    })
    console.log(matrixData)
    // 加入标题拼接最终的数据
    if (matrixData.length > 0 && Array.isArray(matrixData[0])) {
      this.transData = matrixData[0].map((col, i) => {
        return [this.originTitle[i], ...matrixData.map((row) => {
          // 判空处理
          return row[i] !== undefined && row[i] !== null ? row[i] : '';
        })];
      });
      console.log(this.transData);
    } else {
      this.transData = []; // 或者设置为其他默认值
    }
  }
}
</script>

<style>

.el-table__row {
  height: 30px; /* 设置需要的高度 */
}
.blue-background {
  background-color: #156bcd;
}
.blue-background span {
  color: white; /* 设置文字颜色为白色 */
}
/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 12px; /* 水平滚动条的宽度 */
  height: 12px; /* 垂直滚动条的高度 */
  cursor: pointer; /* 鼠标靠近滚动条时变为小手样式 */
}

::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道的颜色 */
  cursor: pointer; /* 鼠标靠近滚动条轨道时变为小手样式 */
}

::-webkit-scrollbar-thumb {
  background: #888; /* 滚动条滑块的颜色 */
  border-radius: 6px; /* 滚动条滑块的圆角 */
  cursor: pointer; /* 鼠标靠近滚动条滑块时变为小手样式 */
}

::-webkit-scrollbar-thumb:hover {
  background: #555; /* 滚动条滑块悬停时的颜色 */
  cursor: pointer; /* 鼠标悬停在滚动条滑块上时仍保持小手样式 */
}
.image {
  width: 38px;
  height: 38px;
  display: block;
  background-size: cover;
}
.image1 {
  width: 50px;
  height: 20px;
  display: block;
  background-size: cover;
/*  margin: 15px 40px; !* 调整图片的上下间距 *!*/
}

/* 刷新频率样式 */
.titleOverview{
  margin-right: 371px;
  font-size: 35px;
  color: #4a6d9a;
}

.dropdown{
  float: right;
}
.frequency{
  font-size: 14px;
  margin-right: 15px;
}

/*分割线*/
.el-divider1{
  margin-top: 15px;
  margin-bottom: 60px;
}
.el-divider2{
  margin-top: 0px;
  margin-bottom: 0px;
}

/*流程样式*/
.card {
  display: flex;
  flex-direction: row;
  position: relative; /* 添加相对定位 */
}
.cardInfo1{
  border: 2px solid #156bcd; /* 添加边框 */
  height: 50px;
  font-size: 16px;
  line-height: 50px;
/*  float: left;*/
  width: 50%;
}

.cardInfo2{
/*  float: right;*/
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  width: 50%;
}
.lamp1{
  position: absolute;
  left: 25%; /* 水平居中 */
  transform: translateX(-50%); /* 调整水平位置 */
  top: 60px; /* 调整垂直位置，使其在 cardInfo1 下方 */
}
.lamp2{
  position: absolute;
  left: 25%; /* 水平居中 */
  transform: translateX(-50%); /* 调整水平位置 */
  top: -40px; /* 调整垂直位置，使其在 cardInfo1 下方 */
}
.odd-index1{
  position: absolute;
  left: 35%; /* 水平居中 */
  transform: translateX(-50%); /* 调整水平位置 */
  top: -40px; /* 调整垂直位置，使其在 cardInfo1 下方 */
}
.even-index1{
  position: absolute;
  left: 15%; /* 水平居中 */
  transform: translateX(-50%); /* 调整水平位置 */
  top: -40px; /* 调整垂直位置，使其在 cardInfo1 下方 */
}
.odd-index2{
  position: absolute;
  left: 35%; /* 水平居中 */
  transform: translateX(-50%); /* 调整水平位置 */
  top: 60px; /* 调整垂直位置，使其在 cardInfo1 下方 */
}
.even-index2{
  position: absolute;
  left: 15%; /* 水平居中 */
  transform: translateX(-50%); /* 调整水平位置 */
  top: 60px; /* 调整垂直位置，使其在 cardInfo1 下方 */
}
.middle{
  height: 100px;
}
.children1{
/*  float: left;*/
  margin-top: 15px;
  font-size: 18px;
  width: 15%;
}
.children2{
  height: 100%;
  width: 100%;
/*  float: left;*/
}
/*表格样式*/
.last-row {
  height: 80px;
}
.top-box .el-table__row {
  height: 50px; /* 设置每一行的高度 */
}
</style>
